import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_test1/api/http/http.dart';
import 'package:flutter_test1/api/http/http_request.dart';
import 'package:flutter_test1/bean/BaseBean.dart';
import 'package:flutter_test1/bean/BaseObject.dart';
import 'package:flutter_test1/constant/Constant.dart';
import 'package:flutter_test1/constant/event.dart';
import 'package:flutter_test1/preference/PreferencesManager.dart';
import 'package:flutter_test1/utils/eventBus.dart';
import 'package:flutter_test1/widget/EditCategoryDialog.dart';

class MineWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return _MineWidget();
  }
}

class _MineWidget extends State<MineWidget> {

  late StreamSubscription<EventData<String>> subscription;
  String title = "我的";
  List<BaseObject> list_category = [];
  int pageSize = 10;
  int page = 1;
  late Future get_category;

  @override
  void initState() {
    super.initState();
    get_category = getData();

    subscription = MyEventBus.instance.on<EventData<String>>().listen((event) {
      if (event.type == EVENT_FORM) {
        if (event.childType == null) {
          return;
        }
        if (event.childType == EVENT_SET_MINE_TITLE) {
          print(event.data);
          title = event.data!;
          setState(() {

          });
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title,style: TextStyle(color: Colors.white),),
        leading: null,
        centerTitle: true,
        primary:false,
        actions: [
          IconButton(onPressed: () async {
            String? name = await EditCategoryDialog.showCategoryName(context);
            if(name != null){
              addCategory(name, "https://qin.tutuyoudian.cn/FsG6mUYvKXkh9VYJG-W4wwBqjojg");
            }
          }, icon: Icon(Icons.add))
        ],
      ),
      body: Container(
        child: Column(
          children: [
            Text("常用组件："),
            RaisedButton(onPressed: (){
              Navigator.pushNamed(context, "WebView");
            },child: Text("WebView"),),
            Divider(
              height: 1,
              color: Color(0xffdddddd),
            ),
            Expanded(
              flex: 1,
              child: FutureBuilder(
                builder: _futureBuilder,
                future: get_category,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _futureBuilder(BuildContext context,AsyncSnapshot snapshot){
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.active:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.waiting:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        return Container(
          child: ListView.builder(
            itemCount: list_category.length,
            itemBuilder: (BuildContext context, int index) {
              BaseObject item = list_category[index];
              return Slidable(
                actionPane: SlidableDrawerActionPane(),
                secondaryActions: [
                  IconSlideAction(
                    caption: "删除",
                    color: Colors.red,
                    icon: Icons.delete,
                    onTap: () async {
                      var result = await showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              title: Text("提示"),
                              content: Text("确定要将 ${item.typeName} 分类删除么"),
                              actions: [
                                FlatButton(
                                  onPressed: (){
                                    Navigator.pop(context,"cancel");
                                  },
                                  child: Text("取消"),
                                ),
                                FlatButton(
                                  onPressed: (){
                                    Navigator.pop(context,"yes");
                                  },
                                  child: Text("确定"),
                                )
                              ],
                            );
                          }
                      );
                      if(result == "yes"){
                        bool delete_result = await deleteCategory(item.id);
                        if(delete_result){
                          setState(() {
                            list_category.remove(item);
                          });
                        }
                      }
                    },
                  )
                ],
                child: GestureDetector(
                  onTap: () async {
                    String? name = await EditCategoryDialog.showCategoryName(context,categoryName: item.typeName);
                    if(name != null){
                      updateCategory(name,"https://qin.tutuyoudian.cn/FsG6mUYvKXkh9VYJG-W4wwBqjojg",item.id);
                    }
                  },
                  child: Container(
                    child: Padding(padding: EdgeInsets.all(20.0),
                      child:  Row(
                        children: [
                          ClipOval(
                            child: Image.network(item.goodsTypeImage,fit: BoxFit.cover,width: 60, height: 60,),
                          ),
                          Expanded(
                              flex: 1,
                              child: Padding(
                                padding: EdgeInsets.only(left: 20.0),
                                child: Text(item.typeName,maxLines: 1,overflow:TextOverflow.ellipsis),
                              )
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      default:
        return Container();
    }
  }

  Future getData() async {
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().categoryList(defaultCurrent: page,pageSize: pageSize, shopId: PreferencesManager.getInstance().getString(Constants.SHOPID));
    if(result.checkRequestSuccess()){
      list_category = result.data!.data!.list!;
      setState(() {

      });
    }
    return result;
  }

  Future<bool> addCategory(String typeName,String  imageUrl) async {
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().addCategory(shopId: PreferencesManager.getInstance().getString(Constants.SHOPID),typeName: typeName,goodsTypeImage: imageUrl);
    if(result.checkSuccessAndToast()){
      getData();
      return true;
    }else{
      return false;
    }
  }

  Future<bool> updateCategory(String typeName,String  imageUrl,String id) async {
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().updateCategory(shopId: PreferencesManager.getInstance().getString(Constants.SHOPID),typeName: typeName,goodsTypeImage: imageUrl, shopGoodsTypeId: id);
    if(result.checkSuccessAndToast()){
      getData();
      return true;
    }else{
      return false;
    }
  }

  Future<bool> deleteCategory(String id) async {
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().deleteCategory(shopGoodsTypeId: id);
    if(result.checkSuccessAndToast()){
      return true;
    }else{
      return false;
    }
  }
}